package com.xinya.taobaosale.ui.presenter.impl;

import android.util.Log;

import com.xinya.taobaosale.model.ApiException;
import com.xinya.taobaosale.model.api.ApiHelper;
import com.xinya.taobaosale.model.domain.ResultBean;
import com.xinya.taobaosale.model.domain.TicketBean;
import com.xinya.taobaosale.model.domain.TicketParams;
import com.xinya.taobaosale.ui.presenter.interfaces.ITicketCallback;
import com.xinya.taobaosale.ui.presenter.interfaces.ITicketPresenter;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @ClassName: TicketPresenterImpl
 * @Description: java类作用描述
 * @Author: mhzhuxinya@163.com
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */
public class TicketPresenterImpl implements ITicketPresenter<ITicketCallback> {
    private static final String TAG = "TicketPresenterImpl";
    public static TicketPresenterImpl INST = new TicketPresenterImpl();

    private TicketPresenterImpl() {
    }

    @Override
    public void onTicketLoaded(String url, String title, String pic_url) {
        TicketParams params = new TicketParams(url, title);
        ApiHelper.INST.mService.getTicket(params).enqueue(new Callback<ResultBean<TicketBean>>() {
            @Override
            public void onResponse(Call<ResultBean<TicketBean>> call, Response<ResultBean<TicketBean>> response) {
                ResultBean<TicketBean> body = response.body();
                if (body == null) {
                    Log.e(TAG, "onResponse: body为空");
                    loadError();
                    return;
                }
                Log.d(TAG, "onResponse: 请求成功");
                try {
                    TicketBean ticketBean = body.getData();
                    for (ITicketCallback callback : callbackList) {
                        callback.getTicket(ticketBean, pic_url);
                    }
                } catch (ApiException e) {
                    e.printStackTrace();
                    loadError();
                }
            }

            @Override
            public void onFailure(Call<ResultBean<TicketBean>> call, Throwable t) {
                Log.e(TAG, "onFailure: 请求失败");
                loadError();
            }
        });
    }

    private void loadError() {
        for (ITicketCallback callback : callbackList) {
            callback.onLoadError(-1);
        }
    }

    private List<ITicketCallback> callbackList = new ArrayList<>();

    @Override
    public void register(ITicketCallback callback) {
        if (callbackList.contains(callback)) {
            return;
        }
        callbackList.add(callback);
    }

    @Override
    public void unRegister(ITicketCallback callback) {
        callbackList.remove(callback);
    }


}
